<template>
  <a-button
    v-if="!isWeightsChange && hasWeightsChangeAuth"
    class="button__weights"
    @click="isWeightsChange = true"
  >
    权重调整
  </a-button>
  <Table v-if="tableProps.dataSource" class="table" :tableProps="tableProps">
    <template #custom="{ record, column, text }">
      <a-input
        v-if="
          isWeightsChange &&
          /^level(\d+)Weights$/.test(column.dataIndex) &&
          (column.dataIndex !== `level${record.nodeLevel}Weights` ||
            record.canApproval)
        "
        v-model:value="
          record[
            `level${
              column.dataIndex.match(/^level(\d+)Weights$/)?.[1] ||
              record.nodeLevel
            }Data`
          ].weights
        "
        suffix="%"
        class="input-cell"
      >
      </a-input>
      <component
        v-else
        :is="column.dataIndex === `level${record.nodeLevel}Name` ? 'a' : 'span'"
        v-bind="
          column.dataIndex === `level${record.nodeLevel}Name`
            ? {
                href: record.id
                  ? `/file/indicator/${record.id?.replace(
                      'I-',
                      ''
                    )}/indicator.html`
                  : undefined,

                target: '_blank',
              }
            : {}
        "
        :title="
          column.customRender?.({
            text,
            record,
            column,
          }) || text
        "
        >{{
          column.customRender?.({
            text,
            record,
            column,
          }) ||
          text ||
          "-"
        }}</component
      >
    </template>
  </Table>
  <div v-if="isWeightsChange" class="buttons">
    <a-button type="primary" class="button__submit" @click="handleSubmit">
      提交
    </a-button>
    <a-button
      class="button__submit"
      @click="
        isWeightsChange = false;
        $router.replace({ name: $route.name || '', params: $route.params });
      "
    >
      取消
    </a-button>
  </div>
</template>
<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { getIndicatorSystemDetailById, updateIndicatorWeights } from "@/api";
import { useRoute, useRouter } from "vue-router";
import { getIndicatorColumns } from "./config";
import Table from "@/components/Table.vue";
import { message } from "ant-design-vue";
import { useUserInfo } from "@/store";
const tableProps = reactive<{
  columns: ColumnItem[];
  dataSource: Record<string, any>[];
  pagination: boolean;
  bordered: boolean;
  rowKey: string;
}>({
  rowKey: "id",
  columns: [],
  dataSource: [],
  pagination: false,
  bordered: true,
});
const route = useRoute();
const router = useRouter();
const userStore = useUserInfo();
const { $loading } =
  getCurrentInstance()?.appContext?.config.globalProperties || {};
const originData = ref<Record<string, any>[]>([]);
const hasWeightsChangeAuth = ref(false);
onMounted(() => {
  isWeightsChange.value = route.query.isWeightsChange === "true";
});
const isWeightsChange = ref(false);
const transformTree2Array = (treeData: Record<string, any>) => {
  let maxLayer = 0;
  const list: Record<string, any>[] = [];
  /**
   * @description: 根据最后一项数据更新前面同level的数据span
   */
  const updateLastData = (index: number, lastItem: any) => {
    if (lastItem) {
      let k = list.length - 2;
      let span = 1;
      while (
        list[k]?.[`level${index + 1}Name`] === lastItem[`level${index + 1}Name`]
      ) {
        span++;
        k--;
      }
      list[k + 1][`level${index + 1}Span`] = span;
    }
  };
  const basicDataSymbol = Symbol("basicData");
  const getTableData = (treeData: any, layer = 1) => {
    const { id, name, weights, canApproval } = treeData;
    const base = {
      ...treeData[basicDataSymbol],
      [`level${layer}Name`]: name,
      [`level${layer}Weights`]: weights,
      [`level${layer}Data`]: treeData, // 保存住这个指针
    };
    if (maxLayer < layer) maxLayer = layer;
    if (treeData.nodeType === 1) {
      const res: Record<string, any> = {
        ...base,
        nodeLevel: layer,
        score: 100,
        weightsScore: weights,
        canApproval,
        id,
      };
      const lastItem = list[list.length - 1]; // 最后一项
      new Array(layer).fill(0).forEach((item, index) => {
        if (
          res[`level${index + 1}Name`] === lastItem?.[`level${index + 1}Name`]
        ) {
          res[`level${index + 1}Span`] = 0;
        } else {
          updateLastData(index, lastItem);
        }
      });
      list.push(res);
      return;
    }
    if (!treeData.children?.length) {
      list.push({
        ...treeData[basicDataSymbol],
        ...base,
      });
      return;
    }
    treeData.children.forEach((item: any) => {
      item[basicDataSymbol] = base; // 隐藏属性，不影响最终提交参数
      getTableData(item, layer + 1);
    });
  };

  treeData.forEach((item: Record<string, any>) => {
    getTableData(item);
  });
  // 根据最后一项更新内容
  const lastItem = list[list.length - 1];
  if (list[list.length - 2]?.[`level1Name`] === lastItem?.[`level1Name`]) {
    new Array(lastItem.nodeLevel).fill(0).forEach((item, index) => {
      updateLastData(index, lastItem);
    });
  }
  return { list, maxLayer };
};
const getData = () => {
  $loading?.start();
  return getIndicatorSystemDetailById(+route.params.id)
    .then((res) => {
      originData.value = res.indicators;
      if (res.userId === userStore.userInfo.userId)
        hasWeightsChangeAuth.value = true;
      const { list, maxLayer } = transformTree2Array(res.indicators);
      tableProps.columns = getIndicatorColumns(maxLayer);
      tableProps.dataSource = list;
    })
    .catch(console.error)
    .finally(() => $loading?.stop());
};
if (route.params.id) {
  getData();
}
const handleSubmit = () => {
  $loading?.start();
  updateIndicatorWeights({
    systemId: +route.params.id,
    indicators: originData.value,
  })
    .then(() => {
      message.success("修改成功");
      getData();
      isWeightsChange.value = false;
      router.replace({ name: route.name || "", params: route.params });
    })
    .catch((e) => {
      console.error(e);
      if (!e.message || e.message.startsWith("/api/indicator"))
        message.error("修改失败");
      $loading?.stop();
    });
};
</script>
<style lang="scss" scoped>
.table {
  margin: 16px 0;
}
.button__weights {
  float: right;
  margin-bottom: 8px;
}
.button__submit {
  margin: 0 8px;
}
.input-cell {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}
.buttons {
  width: 100%;
  text-align: center;
}
</style>
